import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.Queue;
import javax.jms.QueueConnectionFactory;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import com.sun.messaging.jmq.jmsserver.core.Session;

public class Main {

	public static void main(String[] args) {

		new Main().getMessages();
	}

	public void getMessages() {
		Context jndiContext = null;
		ConnectionFactory connectionFactory = null;
		Queue queue = null;
		try {
			jndiContext = new InitialContext();
		} catch (NamingException e) {
			System.out.println("nu putem crea contextul JNDI API "
					+ e.getMessage());
		}
		try {
			connectionFactory = (QueueConnectionFactory) jndiContext
					.lookup("jms/Firstjms");
			queue = (Queue) jndiContext.lookup("jms/Firstjmsqueue");
		} catch (NamingException e) {
			System.out.println("cautare esuata in JNDI API: " + e.getMessage());
		}

		Connection connection;
		MessageConsumer messageConsumer;
		

		try {
			connection = connectionFactory.createConnection();

			javax.jms.Session session = connection.createSession(false,
					Session.AUTO_ACKNOWLEDGE);
			messageConsumer = session.createConsumer(queue);

			messageConsumer.setMessageListener(new ExampleMessageListener());

			connection.start();
			System.out.println("urmatoarea linie de cod permite implementarii"
					+ " lui MessageListener primirea si "
					+ "procesarea mesajelor din coada");
			Thread.sleep(1000);
			System.out.println("codul nu este blocat "
					+ "cat timp receptionam mesaje.");

			Thread.sleep(1000);
			messageConsumer.close();
			session.close();
			connection.close();
		} catch (JMSException | InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/*
	 * (non-Java-doc)
	 * 
	 * @see java.lang.Object#Object()
	 */
	public Main() {
		super();
	}

}